package com.ssm.spring.service.impl;

import com.ssm.spring.dao.BookDao;
import com.ssm.spring.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Author  zxy
 * Date  2022/11/14 下午 4:22
 */
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    /*
    * 事务注解：@Transactional()
    *   只读：readOnly = true
    *   超时：timeout = 3   超时强制回滚
    *   回滚策略：rollbackFor/noRollbackFor(ClassName)
    *           注：默认所有运行时异常都回滚
    *
    *   事务隔离级别：isolation 4个
    *   属性传播行为：propagation
    * */
    @Override
    @Transactional(
            // readOnly = true
            // timeout = 3
            // noRollbackFor = {ArithmeticException.class}
            // isolation = Isolation.DEFAULT
            propagation = Propagation.REQUIRES_NEW
    )
    public void buyBook(Integer userId, Integer bookId) {
        /*
        * 一个sql，一个事务
        * */
        // 查询图书价格
        Integer price = bookDao.getPriceByBookId(bookId);
        // 更新图书库存
        bookDao.updateStock(bookId);
        // 更新用户余额
        bookDao.updateBalance(userId, price);
    }
}
